import 'package:flutter/material.dart';
import 'package:study_app/models/models.dart';
import 'package:study_app/scenes/main_parts/custom_read_page.dart';
import 'package:study_app/tools/tools.dart';

class DemoReader extends StatefulWidget {
  final DataListModel model;
  const DemoReader({Key? key, required this.model}) : super(key: key);
  @override
  State<DemoReader> createState() => _DemoReaderState();
}

class _DemoReaderState extends State<DemoReader> {
  String readStatus = "开始阅读";

  @override
  void dispose() {
    super.dispose();
    _stopRead();
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          title: Text(widget.model.name),
          actions: [_startbutton(), _rightButton(widget.model)]),
      body: scrollViewPageBody(_childNode(), padding: const EdgeInsets.all(16)),
    );
  }

  _childNode() {
    return Column(
      children: [Text(widget.model.detailText)],
    );
  }

  _startbutton() {
    return TextButton(
        onPressed: () {
          _startRead();
        },
        child: Text(
          readStatus,
          style: const TextStyle(color: Colors.white),
        ));
  }

  Widget _rightButton(DataListModel m) {
    return TextButton(
        onPressed: () {
          Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (BuildContext context) =>
                      CustomReader(readText: m.detailText)));
        },
        child: const Text("修改", style: TextStyle(color: Colors.white)));
  }

  _startRead() {
    Tool.startSpeech(widget.model.detailText);
  }

  _stopRead() {
    Tool.stopSpeech();
  }

  Widget scrollViewPageBody(scrolChild,
      {bottom,
      EdgeInsets? margin,
      EdgeInsets? padding,
      Color? bgColor,
      void Function()? pulldown}) {
    Widget scrollView = SingleChildScrollView(
      physics: const AlwaysScrollableScrollPhysics(),
      child: scrolChild,
    );

    if (pulldown != null) {
      scrollView = RefreshIndicator(
        onRefresh: () async {
          pulldown();
        },
        child: scrollView,
      );
    }
    var scrollBackColor = Colors.white;
    List<Widget> arr = [
      Expanded(
          child: Container(
        color: scrollBackColor,
        padding: padding,
        margin: margin,
        child: scrollView,
      ))
    ];
    if (bottom is Widget) {
      arr.add(bottom);
      arr.add(const SizedBox(height: 24));
    }
    return Column(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: arr,
    );
  }
}
